package org.jeecg.modules.hc.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.hc.entity.HcCommodity;
import org.jeecg.modules.hc.entity.HcOrderDetailed;
import org.jeecg.modules.hc.enums.HcUpFlagEnum;
import org.jeecg.modules.hc.service.IHcCommodityService;
import org.jeecg.modules.hc.service.IHcOrderDetailedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: 商品
 * @Author: jeecg-boot
 * @Date: 2022-12-13
 * @Version: V1.0
 */
@Api(tags = "商品")
@RestController
@RequestMapping("/hc/hcCommodity")
@Slf4j
public class HcCommodityController extends JeecgController<HcCommodity, IHcCommodityService> {
    @Autowired
    private IHcCommodityService hcCommodityService;

    @Autowired
    private IHcOrderDetailedService hcOrderDetailedService;

    @ApiOperation("获取菜品分类数量")
    @GetMapping(value = "/getStatistics")
    public Result<?> getStatistics() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<HcCommodity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!"admin".equals(sysUser.getUsername())) {
            lambdaQueryWrapper.eq(HcCommodity::getMerchantId, sysUser.getId());
        }
        long allCount = hcCommodityService.count(lambdaQueryWrapper);

        lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!"admin".equals(sysUser.getUsername())) {
            lambdaQueryWrapper.eq(HcCommodity::getMerchantId, sysUser.getId());
        }
        long yesCount = hcCommodityService.count(lambdaQueryWrapper.eq(HcCommodity::getUpFlag, HcUpFlagEnum.YES));

        lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!"admin".equals(sysUser.getUsername())) {
            lambdaQueryWrapper.eq(HcCommodity::getMerchantId, sysUser.getId());
        }
        long noCount = hcCommodityService.count(lambdaQueryWrapper.eq(HcCommodity::getUpFlag, HcUpFlagEnum.NO));

        lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!"admin".equals(sysUser.getUsername())) {
            lambdaQueryWrapper.eq(HcCommodity::getMerchantId, sysUser.getId());
        }
        long limitCount = hcCommodityService.count(lambdaQueryWrapper.ge(HcCommodity::getLimitBuy, 1));

        JSONObject result = new JSONObject();
        result.put("allCount", allCount);
        result.put("yesCount", yesCount);
        result.put("noCount", noCount);
        result.put("limitCount", limitCount);

        return Result.OK(result);
    }

    @ApiOperation("获取商家菜品")
    @GetMapping(value = "/getMerchantList")
    public Result<IPage<HcCommodity>> getMerchantList(HcCommodity hcCommodity,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Page<HcCommodity> page = new Page<HcCommodity>(pageNo, pageSize);

        LambdaQueryWrapper<HcCommodity> lambdaQueryWrapper = new LambdaQueryWrapper<HcCommodity>()
                .eq(HcCommodity::getMerchantId, sysUser.getId())
                .last("order by SORT is null, SORT, ID");

        if (StringUtils.isNotBlank(hcCommodity.getTradeName())) {
            lambdaQueryWrapper.like(HcCommodity::getTradeName, hcCommodity.getTradeName());
        }

        if (hcCommodity.getUpFlag() != null) {
            lambdaQueryWrapper.like(HcCommodity::getUpFlag, hcCommodity.getUpFlag());
        }

        if (hcCommodity.getLimitBuy() != null) {
            lambdaQueryWrapper.ge(HcCommodity::getLimitBuy, 1);
        }

        IPage<HcCommodity> pageList = hcCommodityService.page(page, lambdaQueryWrapper);

        for (HcCommodity record : pageList.getRecords()) {
            hcCommodityService.setInformation(record, null);

            //获取已售数量
            HcOrderDetailed hcOrderDetailed = hcOrderDetailedService.getOne(new QueryWrapper<HcOrderDetailed>()
                    .select("ifnull(sum(COMMODITY_QUANTITY), 0) as COMMODITY_QUANTITY")
                    .eq("COMMODITY_ID", record.getId())
            );

            if (hcOrderDetailed != null) {
                record.setSoldCount(hcOrderDetailed.getCommodityQuantity());
            }
        }

        return Result.OK(pageList);
    }

    /**
     * 分页列表查询
     *
     * @param hcCommodity
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@AutoLog(value = "商品-分页列表查询")
    @ApiOperation(value = "商品-分页列表查询", notes = "商品-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<HcCommodity>> queryPageList(HcCommodity hcCommodity,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<HcCommodity> page = new Page<HcCommodity>(pageNo, pageSize);
        IPage<HcCommodity> pageList = hcCommodityService.pageList(page, hcCommodity);

        for (HcCommodity record : pageList.getRecords()) {
            hcCommodityService.setInformation(record, null);

            //获取已售数量
            HcOrderDetailed hcOrderDetailed = hcOrderDetailedService.getOne(new QueryWrapper<HcOrderDetailed>()
                    .select("ifnull(sum(COMMODITY_QUANTITY), 0) as COMMODITY_QUANTITY")
                    .eq("COMMODITY_ID", record.getId())
            );

            if (hcOrderDetailed != null) {
                record.setSoldCount(hcOrderDetailed.getCommodityQuantity());
            }
        }

        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hcCommodity
     * @return
     */
    @AutoLog(value = "商品-添加")
    @ApiOperation(value = "商品-添加", notes = "商品-添加")
    //@RequiresPermissions("org.jeecg.modules:hc_commodity:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody HcCommodity hcCommodity) {
        hcCommodity.setCreateTime(new Date());
        hcCommodityService.checkCommodity(hcCommodity);
        hcCommodityService.save(hcCommodity);
        return Result.OK("添加成功！");
    }

    /**
     * 添加
     *
     * @param hcCommodity
     * @return
     */
    @AutoLog(value = "商户端添加菜品")
    @ApiOperation("商户端添加菜品")
    //@RequiresPermissions("org.jeecg.modules:hc_commodity:add")
    @PostMapping(value = "/addByMerchant")
    public Result<String> addByMerchant(@RequestBody HcCommodity hcCommodity) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        hcCommodity.setMerchantId(sysUser.getId());
        hcCommodity.setCreateTime(new Date());
        hcCommodityService.checkCommodity(hcCommodity);
        hcCommodityService.save(hcCommodity);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hcCommodity
     * @return
     */
    @AutoLog(value = "商品-编辑")
    @ApiOperation(value = "商品-编辑", notes = "商品-编辑")
    //@RequiresPermissions("org.jeecg.modules:hc_commodity:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody HcCommodity hcCommodity) {
        hcCommodityService.checkCommodity(hcCommodity);
        hcCommodityService.updateById(hcCommodity);

        //笨比mybatis plus框架，更新null的注解有问题，只能这样写
        hcCommodityService.update(new LambdaUpdateWrapper<HcCommodity>()
                .set(HcCommodity::getCommodityPrice, hcCommodity.getCommodityPrice())
                .set(HcCommodity::getSort, hcCommodity.getSort())
                .eq(HcCommodity::getId, hcCommodity.getId())
        );

        hcCommodityService.setLimitBuy(hcCommodity);
        return Result.OK("编辑成功!");
    }

    /**
     * 批量编辑
     *
     * @return
     */
    @AutoLog(value = "批量编辑")
    @ApiOperation(value = "批量编辑", notes = "批量编辑")
    //@RequiresPermissions("org.jeecg.modules:hc_commodity:edit")
    @PostMapping(value = "/editBatch")
    public Result<String> editBatch(@RequestBody List<HcCommodity> hcCommodityList) {
        for (HcCommodity hcCommodity : hcCommodityList) {
            hcCommodityService.update(new LambdaUpdateWrapper<HcCommodity>()
                    .set(HcCommodity::getTradeName, hcCommodity.getTradeName())
                    .set(HcCommodity::getProductDescription, hcCommodity.getProductDescription())
                    .set(HcCommodity::getProductPicture, hcCommodity.getProductPicture())
                    .set(HcCommodity::getLimitBuy, hcCommodity.getLimitBuy())
                    .set(HcCommodity::getSort, hcCommodity.getSort())
                    .eq(HcCommodity::getId, hcCommodity.getId())
            );

            hcCommodityService.setLimitBuy(hcCommodity);
        }

        //笨比mybatis plus框架，更新null的注解有问题，只能这样写
//        if (hcCommodity.getCommodityPrice() == null) {
//            hcCommodityService.update(new LambdaUpdateWrapper<HcCommodity>()
//                    .set(HcCommodity::getCommodityPrice, null)
//                    .eq(HcCommodity::getId, hcCommodity.getId())
//            );
//        }

        return Result.OK("保存成功!");
    }

    @AutoLog(value = "上下架")
    @ApiOperation("上下架")
    @PostMapping("/editUpFlag")
    public Result<String> editUpFlag(@RequestBody HcCommodity hcCommodity) {
        hcCommodityService.updateById(new HcCommodity().setId(hcCommodity.getId()).setUpFlag(hcCommodity.getUpFlag()));
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "批量上下架")
    @ApiOperation("批量上下架")
    @PostMapping("/editUpFlagBatch")
    public Result<String> editUpFlagBatch(@RequestBody HcCommodity param) {
        List<String> ids = Arrays.asList(param.getSelections().split(","));

        hcCommodityService.update(new HcCommodity().setUpFlag(param.getUpFlag()),
                new LambdaQueryWrapper<HcCommodity>().in(HcCommodity::getId, ids)
        );

        return Result.OK("修改成功!");
    }

    @AutoLog(value = "批量修改库存")
    @ApiOperation("批量修改库存")
    @PostMapping("/editLimitBuyBatch")
    public Result<String> editLimitBuyBatch(@RequestBody List<HcCommodity> param) {
        if (!CollectionUtils.isEmpty(param)) {
            for (HcCommodity hcCommodity : param) {
                hcCommodityService.updateById(new HcCommodity().setId(hcCommodity.getId()).setLimitBuy(hcCommodity.getLimitBuy()));
                hcCommodityService.setLimitBuy(hcCommodity);
            }
        }

        return Result.OK("修改成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "商品-通过id删除")
    @ApiOperation(value = "商品-通过id删除", notes = "商品-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:hc_commodity:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        hcCommodityService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "商品-批量删除")
    @ApiOperation(value = "商品-批量删除", notes = "商品-批量删除")
    //@RequiresPermissions("org.jeecg.modules:hc_commodity:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hcCommodityService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "商品-通过id查询")
    @ApiOperation(value = "商品-通过id查询", notes = "商品-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<HcCommodity> queryById(@RequestParam(name = "id", required = true) String id) {
        HcCommodity hcCommodity = hcCommodityService.getById(id);
        if (hcCommodity == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hcCommodity);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hcCommodity
     */
    //@RequiresPermissions("org.jeecg.modules:hc_commodity:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HcCommodity hcCommodity) {
        return super.exportXls(request, hcCommodity, HcCommodity.class, "商品");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("hc_commodity:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HcCommodity.class);
    }

}
